package com.fzk.blog.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;

import java.util.Random;

/**
 * @author fzk
 * @date 2021-09-10 0:15
 */
@Configuration
public class MyMailSender {
    @Autowired
    private JavaMailSender mailSender;//一定要用@Autowired
    //application.properties中已配置的值
    @Value("${spring.mail.username}")
    private String from;

    /**
     * 给email发验证码
     * @param email 邮箱
     * @return 返回验证码
     */
    public String sendMail(String email) {
        String code=null;
        try {
            SimpleMailMessage mailMessage = new SimpleMailMessage();

            mailMessage.setSubject("验证码邮件");//主题
            //生成6位随机数验证码
            StringBuilder stringBuilder = new StringBuilder();
            Random rand = new Random();
            for (int i = 0; i < 6; ++i)
                stringBuilder.append(rand.nextInt(10));
            code = stringBuilder.toString();

            mailMessage.setText("您收到的验证码是：" + code + "。有效时间为1h，请尽快验证。");//内容

            mailMessage.setTo(email);//发给谁

            mailMessage.setFrom(from);//你自己的邮箱

            mailSender.send(mailMessage);//发送
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return code;
    }
}
